<?php
// +----------------------------------------------------------------------
// | my
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\we\model;

use think\Model;

class WeFans extends Model
{

    
    /**
     * 获取微信配置信息，需要缓存
     */
    public function info($openid,$field=true){
      
      if (is_numeric($openid)){
        $map['id']=$openid;
      }else{
        $map['openid']=$openid;
      }
      $fans = $this->field($field)->where($map)->find();
      //如果是管理员，获取管理员信息
      if ($fans['admin']){
        $admin=model('admin/AdminUser')->info($fans['admin']);
        if ($admin){
          $fans['admin_info']=$admin;
        }
      }

      
      return  $fans;
    }



     public function infoForFans($openid,$field=true){

      $fans=$this->info($openid,$field=true);
      if (!$fans) return false;
      $cfo=model('we/WeFansCfo')->info($openid);
      $printer=model('printer/PrinterFans')->info($fans['openid'],'balance');

      $message="粉丝信息";
      $message.="\nID：".$fans['id'];
      $message.="\n昵称：".$fans['nickname'];
      if($cfo)$message.="\n余额：".$cfo['amount'];
      if($cfo)$message.="\n积分：".$cfo['score'];
      if($printer) $message.="\n打印余额：".$printer['balance'];
      $url=request()->domain().url('we/space/index',['openid'=>$openid]);
      $message.="\n".'<a href="'.$url.'">我的特权</a>';
      if($fans['admin']) {
        $message.="\n------------";
        $message.="\n".$fans['admin_info']['name']."你是本店管理员:";
        $shop=model('admin/AdminShop')->info($fans['admin_info']['shopid']);
        $message.="\n分店:".$shop['title'];
        $message.="\n电话:".$fans['admin_info']['mobile'];
      }
     
      return  ['fans'=>$fans,'message'=>$message];
    }

    public function infoForFansByOrder($data){
     //处理关键词
    
     $fans = $this->infoForFans($data['before']);
     if (!$fans) return ['message'=>'粉丝不存在，请核对粉丝ID'];
     return ['message'=>$fans['message']]; //空尾巴查询
    }

    public function getAdmins($appid){
      $map['appid']=$appid;
      $map['admin']=['NEQ',''];
      $admins=$this->where($map)->select();
      return  $admins;
    }

    public function checkAdmin($openid){
     $fans=$this->info($openid);
     if (!$fans['admin']) {
      return ['status'=>0,'text'=>'请输入手机号FA密码登录'];
     }else{
      $admin=model('admin/AdminUser')->info($fans['admin']);
      return $admin;
     }
     
    }




    public function editData($data){

      
      if (isset($data['id'])){
         $res = $this->allowField(true)->where('id',$data['id'])->update($data);
      }else{
          $res = $this->allowField(true)->data($data)->save();
      }
    
      return $res;
    }

     public function F($data) {
       
      
        

        //普通处理
        $first=substr($data['back'],0,1);
        $um=str_replace($first,"",$data['back']);
        

        if ($first=="A"){
            $hasUser = db('admin_user')->where(array('mobile' => $data['before'],'aid' =>$data['aid']))->find();

            if(empty($hasUser)) return ['message'=>'管理员不存在'];
            if(md5(md5($um) . config('data_auth_key'))!= $hasUser['password']) return ['message'=>'密码错误'];
            if(1 != $hasUser['status']) return ['message'=>'账号被禁用'];
           

            $res=db('WeFans')->where('openid',$data['openid'])->update(['admin'=>$hasUser['id']]);
            if ($res)  return ['message'=>$hasUser['name'].'登录成功'];
            return ['message'=>'不需要重复登录'];

        }


         //其他需要验证权限
        $admin=model('we/WeFans')->checkAdmin($data['openid']);
        if($admin['status']==0) return $admin['text'];

        //消费 (粉丝F1++100)
        if(strstr($data['back'],'+')){
           return $message=model('we/WeFansBuy')->buy($data);
        }  


        $fans=$this->info($data['before']);
        if (!$fans and $first<>'A')return ['message'=>$data['before'].'号粉丝不存在'];
       
        switch ( $first) {
          case 'M':
            return model('we/WeFansCfo')->cfoAmount($fans,$um,$data);
            break;
          case 'S':
            return model('we/WeFansCfo')->cfoScore($fans,$um,$data);
            break;
          case 'C':

            $c_first=mb_substr($um,0,1);
            
            switch ($c_first) {
              case '卡':
                $card_id=str_replace($c_first,"",$um);
                if (!$card_id){
                  $cards=db('WeCard')->where('appid',$data['appid'])->select();
                  $reply='卡券列表：';
                  foreach ($cards as $key => $card) {
                    $reply.="\n".$card['id']."号卡券：".$card['title'];
                  }
                  return ['message'=>$reply];

                }else{
                  $card=model('we/weCard')->info($card_id);
                  $message=['msgtype'=>'wxcard','wxcard'=>['card_id'=>$card['card_id']]];
                }
                
                break;
              
              default:
               
                $message=['msgtype'=>'text','text'=>['content'=>$um]];
                break;
            }
            $error= custom_message($fans['openid'],$message);
            return ['message'=>!$error?'发送成功给'.$fans['nickname']:$error];
           break;
         
          }

          
     }

     public function downAvatar($fans,$w='250',$h='250'){
        $path="uploads/we/avatar";
        createFolder($path);
        $pic_name=$fans['openid'].'.jpg';
        $this_avatar_pic=$path.'/'.$pic_name;
        if (!file_exists($this_avatar_pic)) {
          get_file_from_net($fans['headimgurl'],$path,$pic_name);
          $image = \think\Image::open($this_avatar_pic);
          $image->thumb($w,$h,\think\Image::THUMB_CENTER)->save($this_avatar_pic);
        }
       
        return $this_avatar_pic;
    }


    
}